package org.kisekiproject.evaluator.nodes {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import org.kisekiproject.evaluator.IVariableNamespace;
	import org.kisekiproject.evaluator.events.VariableChangeEvent;

	/**
	 * @author mikael
	 */
	public class VariableNode extends EventDispatcher implements ISyntaxNode {
		private var _variables : IVariableNamespace;
		private var _variable : String;
		private var _index : int;
		private var _getValueCalled:Boolean;

		/**
		 * Constructor.
		 */
		public function VariableNode(variables:IVariableNamespace, variable:String, index:int) {
			_variables=variables;
			_variable=variable;
			_index=index;

			_variables.addEventListener(VariableChangeEvent.VARIABLE_CHANGE, onVariableChange);
			_getValueCalled=false;
		}

		/**
		 * Variable change.
		 */
		private function onVariableChange(event : VariableChangeEvent) : void {
			if (event.variable==_variable)
				dispatchEvent(new Event(Event.CHANGE));
		}

		/**
		 * Get value.
		 */
		public function get value() : Object {
			//trace("getting value of: "+_variable);
			if (_getValueCalled)
				throw new Error("Circular expression");

			_getValueCalled=true;
			var value:Object=_variables.getVariable(_variable);
			_getValueCalled=false;

			return value;
		}

		/**
		 * Get index.
		 */
		public function get index() : int {
			return _index;
		}
	}
}
